package com.universe.datastructure.queue;

import java.util.Scanner;

/**
 * @Description: 数组模拟队列
 * @Author: chenhuan
 * @Date: 21:35 2019/12/6
 * 存在的问题：1.数组使用一次就不能再用
 *             2.将该数组改进成环形队列 实现：取模%
 */
public class ArrayQueueDemo {
    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(3);
        String key = "";
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop) {
            System.out.println("show:显示队列");
            System.out.println("exit:退出程序");
            System.out.println("add:添加数据");
            System.out.println("get:取出数据");
            System.out.println("head:查看队头");
            key = scanner.next();
            switch (key) {
                case "show":
                    queue.showQueue();
                    break;
                case "add":
                    System.out.println("请输入您要添加的数字：");
                    int value = scanner.nextInt();
                    queue.addQueue(value);
                    break;
                case "get":
                    try {
                        System.out.println("取出的数据是：" + queue.getQueue());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case "head":
                    try {
                        System.out.println("对头数据是：" + queue.headQueue());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
    }
}

class ArrayQueue {
    private int[] arr;
    private int maxSize;
    private int front;
    private int rear;

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        front = -1;
        rear = -1;
    }

    public void addQueue(int value) {
        if (isFull()) {
            System.out.println("队列已满，不能再加了");
            return;
        }
        rear++;
        arr[rear] = value;
    }

    public int getQueue() {
        if (isNull()) {
            throw new RuntimeException("队列已空，不能再取了");
        }
        front++;
        return arr[front];
    }

    public void showQueue() {
        if (isNull()) {
            System.out.println("队列为空");
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("arr[%d]=%d\n", i, arr[i]);
        }
    }

    public int headQueue() {
        if (isNull()) {
            throw new RuntimeException("队列已空");
        }
        return arr[front + 1];
    }

    private boolean isNull() {
        return rear == front;
    }

    private boolean isFull() {
        return rear == maxSize - 1;
    }

}
